/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xml.avaliation;

import beans.Avaliation;
import beans.Judge;
import java.beans.IntrospectionException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.betwixt.io.BeanWriter;
import org.xml.sax.SAXException;

public class AvaliationWriter {

    BeanWriter writer;
    FileOutputStream fos;
    StringWriter content;
    Judge judge;

    public AvaliationWriter(Judge judge) {
        this.judge = judge;
    }

    public boolean print(Avaliation avaliation) {
        AvaliationReader avaliationReader = new AvaliationReader(judge);
        List<Avaliation> allAvaliations = avaliationReader.getAllAvaliationsLoggedUser();
        if (allAvaliations == null || allAvaliations.isEmpty()) {
            allAvaliations = new ArrayList<>();
        }
        allAvaliations.add(avaliation);
        return printInXML(allAvaliations);
    }

    public void printAllBeers(List<Avaliation> avaliations) {
        printInXML(avaliations);
    }

    private boolean printInXML(List<Avaliation> avaliations) {
        content = new StringWriter();
        content.write("<?xml version='1.0'?>\r\n");
        content.write("<avaliations>\r\n");
        try {
            writer = new BeanWriter(content);
            writer.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
            writer.enablePrettyPrint();
            writer.getBindingConfiguration().setMapIDs(false);
            writer.start();
            for (Avaliation a : avaliations) {
                writer.write(a);
            }
            writer.end();
            content.write("</avaliations>");
            File f = new File("src\\xml\\avaliation\\avaliations\\" + judge.getName().replaceAll(" ", "_") + ".xml");
            if (!f.exists()) {
                f.createNewFile();
            }
            PrintWriter out = new PrintWriter(f);
            out.print(content);
            out.flush();
            return true;
        } catch (IOException ex) {
            writer = null;
            ex.printStackTrace();
        } catch (SAXException ex) {
            Logger.getLogger(AvaliationWriter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IntrospectionException ex) {
            Logger.getLogger(AvaliationWriter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

//    public void remove(Avaliation a) {
//        BeerReader beerReader = new BeerReader();
//        List<Beer> allBeers = beerReader.getAllBeers();
//        allBeers.remove(b);
//        printAllBeers(allBeers);
//    }
}
